<template>
  <base-table-layout
      title="物资中心"
      :total="total"
      :current-page="currentPage"
      :page-size="pageSize"
      @update:currentPage="val => currentPage = val"
      @update:pageSize="val => pageSize = val"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  >
    <!-- 搜索区域 -->
    <template #search>
      <el-input
          v-model="searchForm.materialName"
          placeholder="物资名称"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleSearch"
      />
      <el-select
          v-model="searchForm.categoryId"
          placeholder="物资类型"
          style="width: 200px; margin-left: 10px;"
          class="filter-item"
          clearable
      >
        <el-option
          v-for="item in categoryOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleSearch"
      >搜索</el-button>
      <el-button
          class="filter-item"
          type="info"
          icon="el-icon-refresh"
          @click="resetSearch"
      >重置</el-button>
    </template>

    <!-- 操作区域 -->
    <template #operation>
      <el-button
          type="success"
          icon="el-icon-plus"
          @click="handleAdd"
      >新增</el-button>
      <el-button
          type="danger"
          icon="el-icon-delete"
          @click="handleBatchDelete"
      >批量删除</el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <el-table
          v-loading="loading"
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column
            type="selection"
            width="56"
        />
        <el-table-column prop="materialName" label="物资名称" width="220" />
        <el-table-column label="物资类型" width="220">
          <template slot-scope="{row}">
            {{ getCategoryName(row.categoryId) }}
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="materialSpecification" label="规格" />
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 弹窗区域 -->
    <template #dialogs>
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
        <el-form :model="materialForm" :rules="rules" ref="materialForm" label-width="100px">
          <el-form-item label="物资名称" prop="materialName">
            <el-input v-model="materialForm.materialName"></el-input>
          </el-form-item>
          <el-form-item label="物资类型" prop="categoryId">
            <el-select v-model="materialForm.categoryId" placeholder="请选择物资类型" style="width: 100%">
              <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="单位" prop="unit">
            <el-input v-model="materialForm.unit"></el-input>
          </el-form-item>
          <el-form-item label="规格" prop="materialSpecification">
            <el-input v-model="materialForm.materialSpecification"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </template>
  </base-table-layout>
</template>

<script>
import request from '@/utils/request'
import _ from 'lodash'
import BaseTableLayout from '@/components/BaseTableLayout.vue'

export default {
  name: 'MaterialMasterView',
  components: {
    BaseTableLayout
  },
  data() {
    return {
      loading: false,
      searchForm: {
        materialName: '',
        categoryId: null
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      materialForm: {
        materialName: '',
        categoryId: null,
        unit: '',
        materialSpecification: ''
      },
      rules: {
        materialName: [
          {required: true, message: '请输入物资名称', trigger: 'blur'}
        ],
        categoryId: [
          {required: true, message: '请选择物资分类', trigger: 'change'}
        ],
        unit: [
          {required: true, message: '请输入单位', trigger: 'blur'}
        ],
        materialSpecification: [
          {required: false, message: '请输入规格', trigger: 'blur'}
        ]
      },
      selectedRows: [],
      categoryOptions: [],
      categoryMap: {}
    }
  },
  methods: {
    async loadCategoryTree() {
      try {
        const res = await request({
          url: '/material/category/tree',
          method: 'get'
        })
        this.categoryOptions = this.formatCategoryOptions(res)
        this.categoryMap = this.createCategoryMap(res)
      } catch (error) {
        console.error('获取分类树失败:', error)
        this.$message.error('获取分类树失败')
      }
    },

    formatCategoryOptions(categories, prefix = '') {
      const options = []
      categories.forEach(category => {
        const option = {
          value: category.categoryId,
          label: prefix + category.categoryName
        }
        options.push(option)
        if (category.children && category.children.length > 0) {
          options.push(...this.formatCategoryOptions(category.children, prefix + '  '))
        }
      })
      return options
    },

    createCategoryMap(categories) {
      const map = {}
      const traverse = (items) => {
        items.forEach(item => {
          map[item.categoryId] = item.categoryName
          if (item.children && item.children.length > 0) {
            traverse(item.children)
          }
        })
      }
      traverse(categories)
      return map
    },

    getCategoryName(categoryId) {
      return this.categoryMap[categoryId] || '-'
    },

    async handleLoadData() {
      try {
        this.loading = true
        const response = await request.get('/material/page', {
          params: {
            page: this.currentPage,
            size: this.pageSize,
            materialName: this.searchForm.materialName || undefined,
            categoryId: this.searchForm.categoryId || undefined
          }
        })

        this.tableData = response.records
        this.total = response.total
      } catch (error) {
        console.error('获取物资数据失败:', error)
        this.$message.error('获取物资数据失败')
        this.tableData = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    handleSearch: _.debounce(async function() {
      this.currentPage = 1
      await this.handleLoadData()
    }, 300),

    async resetSearch() {
      this.searchForm.materialName = ''
      this.searchForm.categoryId = null
      this.currentPage = 1
      await this.handleLoadData()
    },

    handleAdd() {
      this.dialogTitle = '新增物资'
      this.materialForm = {
        materialName: '',
        categoryId: null,
        unit: '',
        materialSpecification: ''
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogTitle = '编辑物资'
      this.materialForm = { ...row }
      this.dialogVisible = true
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该物资信息吗？', '提示', {
          type: 'warning'
        })
        await request.delete(`/material/${row.materialId}`)
        this.$message.success('删除成功')
        await this.handleLoadData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    handleSelectionChange(val) {
      this.selectedRows = val
    },

    async handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要删除的物资')
        return
      }

      try {
        await this.$confirm('确认删除选中的物资吗？', '提示', {
          type: 'warning'
        })
        const materialIds = this.selectedRows.map(row => row.materialId)
        await request.delete('/material/batch', { data: materialIds })
        this.$message.success('批量删除成功')
        await this.handleLoadData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败')
        }
      }
    },

    async handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      await this.handleLoadData()
    },

    async handleCurrentChange(val) {
      this.currentPage = val
      await this.handleLoadData()
    },

    async submitForm() {
      try {
        await this.$refs.materialForm.validate()
        const formData = { ...this.materialForm }

        if (formData.materialId) {
          await request.put('/material', formData)
          this.$message.success('更新成功')
        } else {
          await request.post('/material', formData)
          this.$message.success('添加成功')
        }

        this.dialogVisible = false
        await this.handleLoadData()
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败')
      }
    }
  },
  created() {
    this.loadCategoryTree()
    this.handleLoadData()
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.operation-bar {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.el-button {
  margin-left: 10px;
}

.el-table {
  margin-top: 20px;
}

.el-table th {
  background-color: #f5f7fa;
  color: #909399;
}

.el-table .el-button {
  padding: 7px 15px;
  font-size: 12px;
}

.el-table .el-button + .el-button {
  margin-left: 5px;
}
</style>